package com.zziq.cloudpicturebank.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.zziq.cloudpicturebank.api.aliyunAi.AliYunAiApi;
import com.zziq.cloudpicturebank.api.aliyunAi.model.CreateOutPaintingTaskRequest;
import com.zziq.cloudpicturebank.api.aliyunAi.model.CreateOutPaintingTaskResponse;
import com.zziq.cloudpicturebank.common.BaseResponse;
import com.zziq.cloudpicturebank.config.CosClientConfig;
import com.zziq.cloudpicturebank.constant.RabbitMqConstant;
import com.zziq.cloudpicturebank.constant.RedisKeyConstant;
import com.zziq.cloudpicturebank.exception.BusinessException;
import com.zziq.cloudpicturebank.exception.ErrorCode;
import com.zziq.cloudpicturebank.exception.ThrowUtils;
import com.zziq.cloudpicturebank.manager.upload.CosManager;
import com.zziq.cloudpicturebank.manager.upload.templateImpl.FilePictureUpload;
import com.zziq.cloudpicturebank.manager.upload.template.PictureUploadTemplate;
import com.zziq.cloudpicturebank.manager.upload.templateImpl.UrlPictureUpload;
import com.zziq.cloudpicturebank.model.dto.file.UploadPictureResult;
import com.zziq.cloudpicturebank.model.dto.picture.*;
import com.zziq.cloudpicturebank.model.entity.Picture;
import com.zziq.cloudpicturebank.model.entity.Space;
import com.zziq.cloudpicturebank.model.entity.User;
import com.zziq.cloudpicturebank.model.enums.PictureReviewStatusEnum;
import com.zziq.cloudpicturebank.model.enums.UserRoleEnum;
import com.zziq.cloudpicturebank.model.vo.picture.PictureDownloadResponse;
import com.zziq.cloudpicturebank.model.vo.picture.PictureVO;
import com.zziq.cloudpicturebank.model.vo.user.UserVO;
import com.zziq.cloudpicturebank.service.PictureService;
import com.zziq.cloudpicturebank.mapper.PictureMapper;
import com.zziq.cloudpicturebank.service.SpaceService;
import com.zziq.cloudpicturebank.service.UserService;
import com.zziq.cloudpicturebank.utils.ColorSimilarUtils;
import com.zziq.cloudpicturebank.utils.MyMessageProducer;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author Mr·张
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-02-21 14:53:56
 */
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {
    @Resource
    private UserService userService;

    @Resource
    private FilePictureUpload filePictureUpload;

    @Resource
    private UrlPictureUpload urlPictureUpload;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CosManager cosManager;

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private SpaceService spaceService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private MyMessageProducer myMessageProducer;

    @Resource
    private AliYunAiApi aliYunAiApi;

    //定义本地缓存对象
    private final Cache<String, String> LOCAL_CACHE =
            Caffeine.newBuilder().initialCapacity(1024)
                    .maximumSize(10000L)
                    // 缓存 3-6 分钟移除
                    .expireAfterWrite(180 + RandomUtil.randomInt(0, 180), TimeUnit.SECONDS)
                    .build();

    /**
     * 上传图片
     *
     * @param inputSourse
     * @param pictureUploadRequest
     * @param loginUser
     * @return
     */
    @Override
    public PictureVO uploadPicture(Object inputSourse,
                                   PictureUploadRequest pictureUploadRequest,
                                   User loginUser) {
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        //检验空间是否存在
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null,
                    ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            //校验额度
            Long maxCount = space.getMaxCount();
            if (space.getTotalCount() >= maxCount) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR,
                        "空间已满，您的存储数量上限为:" + maxCount);
            }
            //校验容量
            Long maxSize = space.getMaxSize();
            if (space.getTotalSize() >= maxSize) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR,
                        "空间大小不足,您的存储空间上限为:" + maxSize + "MB");
            }
        }
        // 用于判断是新增还是更新图片
        Long pictureId = pictureUploadRequest.getId();
        Picture oldPicture = new Picture();
        // 如果是更新图片，需要校验图片是否存在
        if (pictureId != null) {
            oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null,
                    ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            //校验空间是否一致
            //没传 spaceId，则复用原有图片的spaceId（兼容公共图库）
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                //传了spaceId，必须和原图片的空间一致
                if (ObjUtil.notEqual(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间id不一致");
                }
            }
        }
        // 上传图片，得到信息
        // 按照用户 id 划分目录
        //默认上传的公共图库
        String uploadPathPrefix = String.format("public/%s", loginUser.getId());
        //如果指定了空间，则上传到空间目录下
        if (spaceId != null) {
            //空间目录
            uploadPathPrefix = String.format("space/%s", spaceId);
        }

        //获取上传图片的模板，默认是使用本地文件上传的方式
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        //判断是否是使用url上传图片
        if (inputSourse instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        //上传图片并返回上传结果（包括图片信息）
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSourse, uploadPathPrefix);
        // 构造要入库的图片信息
        Picture picture = new Picture();
        picture.setSpaceId(spaceId);
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        picture.setOriginUrl(uploadPictureResult.getOriginUrl());
        String picName = uploadPictureResult.getPicName();
        //支持外层传递图片名称
        if (pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());
        //补充审核参数
        fillReviewParams(picture, loginUser);
        Long finalSpaceId = spaceId;
        Long finalPictureId = pictureId;
        Picture finalOldPicture = oldPicture;
        // 入库,开启事务
        transactionTemplate.execute(status -> {
            boolean result;
            // 如果 pictureId 不为空，表示更新，否则是新增
            // 1.更新图片
            if (finalPictureId != null) {
//                Picture oldPicture = this.getById(finalPictureId);
                if (finalSpaceId == null) {
                    // 1.1：表示上传到公共图库
                    //因为是更新，需要补充 id 和编辑时间
                    picture.setId(finalPictureId);
                    picture.setEditTime(new Date());
                    // 更新数据库信息
                    result = this.updateById(picture);
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败,数据库操作失败！");
                    // 删除云存储对象中的图片
                    // （注意这里可以不用判断图片的url是否更新，内部函数clearPictureFile 会做出判断）
                    clearPictureFile(finalOldPicture);
                    //清理缓存
                    clearCaffineAndRedisCache(RedisKeyConstant.HONE_PAGE_CACHE_KEY, RedisKeyConstant.HONE_PAGE_CACHE_KEY);
                } else {
                    // 1.2：表示上传到个人空间
                    //更新空间的使用额度
                    result = spaceService.lambdaUpdate()
                            .eq(Space::getId, finalSpaceId)
                            .setSql("totalSize = totalSize + " + picture.getPicSize())
                            .setSql("totalSize = totalSize - " + this.getById(pictureUploadRequest.getId()).getPicSize())
                            .update();
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败,空间额度更新失败，数据库操作失败！");
                    //因为是更新，需要补充 id 和编辑时间
                    picture.setId(finalPictureId);
                    picture.setEditTime(new Date());
                    // 更新数据库信息
                    result = this.updateById(picture);
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败,数据库操作失败！");
                    // 删除云存储对象中的图片
                    // （注意这里可以不用判断图片的url是否更新，内部函数clearPictureFile 会做出判断）
                    clearPictureFile(finalOldPicture);
                }
            }
            // 2.新增图片
            else {
                if (finalSpaceId == null) {
                    //2.1：表示上传到公共图库
                    result = this.save(picture);
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败,数据库操作失败！");
                    //清理缓存
                    clearCaffineAndRedisCache(RedisKeyConstant.HONE_PAGE_CACHE_KEY, RedisKeyConstant.HONE_PAGE_CACHE_KEY);
                } else {
                    // 2.2：表示上传到个人空间
                    //新增数据库信息
                    picture.setShareExpireTime(new Date());
                    result = this.save(picture);
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败,数据库操作失败！");
                    //更新空间的谁用额度
                    result = spaceService.lambdaUpdate()
                            .eq(Space::getId, finalSpaceId)
                            .setSql("totalSize = totalSize + " + picture.getPicSize())
                            .setSql("totalCount = totalCount + 1")
                            .update();
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "额度更新失败,数据库操作失败！");
                }
            }
            return result;
        });

        Long id = picture.getId();
        //发送mq消息
        //对于创建私人空间（包括团队空间）的图片，需添加主调色计算
        if (spaceId != null){
            myMessageProducer.sendMessage(
                    RabbitMqConstant.CALCULATE_PICCOLOR_EXCHANGE,
                    RabbitMqConstant.CALCULATE_PICCOLOR_ROUTING_KEY,
                    picture.getId()
            );
        }
        return PictureVO.objToVo(picture);
    }

    /**
     * 更新图片
     *
     * @param pictureUpdateRequest
     * @param loginUser
     * @return
     */
    @Override
    public boolean updatePicture(PictureUpdateRequest pictureUpdateRequest, User loginUser) {
        Long pictureId = pictureUpdateRequest.getId();
        //获取原始图片对象
        Picture oldPicture = this.getById(pictureId);
        // 判断是否存在
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        //校验权限
        this.checkPictureAuth(loginUser, oldPicture);
        // 将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        // 数据校验
        this.validPicture(picture);
        //补充审核参数
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        //判断是否是公共图库图片
        if (oldPicture.getSpaceId() == null) {
            //清理缓存
            clearCaffineAndRedisCache(RedisKeyConstant.HONE_PAGE_CACHE_KEY,
                    RedisKeyConstant.HONE_PAGE_CACHE_KEY);
        }
        return result;
    }

    /**
     * 封装查询条件
     *
     * @param pictureQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();

        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "spaceId");
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        // >= startEditTime
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        // <= endEditTime
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }


    /**
     * 图片对象转图片封装（单条）
     *
     * @param picture
     * @param request
     * @return
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * 分页获取图片封装（多条）
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    /**
     * 校验图片合法性
     *
     * @param picture
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    /**
     * 图片审核
     *
     * @param pictureReviewRequest
     * @param loginUser
     */
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        if (id == null || reviewStatusEnum == null || PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 已是该状态
        if (oldPicture.getReviewStatus().equals(reviewStatus)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请勿重复审核");
        }

        // 更新审核状态
        Picture updatePicture = new Picture();
        BeanUtils.copyProperties(pictureReviewRequest, updatePicture);
        updatePicture.setReviewerId(loginUser.getId());
        updatePicture.setReviewTime(new Date());
        boolean result = this.updateById(updatePicture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        //判断是否是公共图库图片
        if (oldPicture.getSpaceId() == null) {
            //清理缓存
            clearCaffineAndRedisCache(RedisKeyConstant.HONE_PAGE_CACHE_KEY,
                    RedisKeyConstant.HONE_PAGE_CACHE_KEY);
        }
    }

    /**
     * 填充审核状态信息
     *
     * @param picture
     * @param loginUser
     */
    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        if (userService.isAdmin(loginUser)) {
            // 管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewTime(new Date());
        } else {
            // 非管理员，创建或编辑都要改为待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    /**
     * 批量上传图片
     *
     * @param pictureUploadByBatchRequest
     * @param loginUser
     * @return
     */
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        //用户输入的关键词
        String searchText = pictureUploadByBatchRequest.getSearchText();
        //将用户给的图片名称前缀赋值
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        //如果用户没给图片名称前缀，默认为搜索词
        if (StrUtil.isBlank(namePrefix)) {
            //前缀默认为搜索词
            namePrefix = searchText;
        }
        // 格式化数量
        Integer count = pictureUploadByBatchRequest.getCount();
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "最多 30 条");
        // 要抓取的地址
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        //定义 Document 对象
        Document document;
        try {
            log.info("开始抓取页面: {}", fetchUrl);
            // 获取页面
            document = Jsoup.connect(fetchUrl)
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0")
                    .get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        // 获取 div 标签
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }
        // 获取 div 标签中的img 标签
        Elements imgElementList = div.select("img.mimg");
        //用于记录上传图片的数量
        int uploadCount = 0;
        for (Element imgElement : imgElementList) {
            // 获取图片地址
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过: {}", fileUrl);
                continue;
            }
            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            if (StrUtil.isNotBlank(namePrefix)) {
                // 设置图片名称，序号连续递增
                pictureUploadRequest.setPicName(namePrefix + (uploadCount + 1));
            }
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功, id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        //清理缓存
        clearCaffineAndRedisCache(RedisKeyConstant.HONE_PAGE_CACHE_KEY,
                RedisKeyConstant.HONE_PAGE_CACHE_KEY);

        return uploadCount;
    }

    /**
     * 分页获取封装图片列表（带缓存）
     *
     * @param pictureQueryRequest
     * @param request
     * @return
     */
    @Override
    public Page<PictureVO> listPictureVOByPageWithCache(PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        //判断是否可以走缓存
        if(pictureQueryRequest.getCategory() != null ||
                pictureQueryRequest. getTags() != null ||
                    StrUtil.isNotBlank(pictureQueryRequest.getSearchText())){
            //查询条件变更，不可以走缓存
            //1、查询数据库
            Page<Picture> picturePage =
                    this.page(new Page<>(pictureQueryRequest.getCurrent(), pictureQueryRequest.getPageSize()),
                            this.getQueryWrapper(pictureQueryRequest));
            //2、获取封装类并返回
            return this.getPictureVOPage(picturePage, request);
        }
        //可以走缓存（除了页数查询条件未变更）
        // 1.构建缓存 key
        String cacheKey = RedisKeyConstant.HONE_PAGE_CACHE_KEY+pictureQueryRequest.getCurrent();
        //2.从本地缓存Caffine中查询数据
        String cachedValue = LOCAL_CACHE.getIfPresent(cacheKey);
        if (cachedValue != null) {
            // 如果缓存命中，返回结果
            return JSONUtil.toBean(cachedValue, Page.class);
        }

        //3.从redis中查询数据
        ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
        cachedValue = valueOps.get(cacheKey);
        if (cachedValue != null) {
            //存入本地缓存
            LOCAL_CACHE.put(cacheKey, cachedValue);
            //返回结果
            return JSONUtil.toBean(cachedValue, Page.class);
        }

        // 4.查询数据库
        Page<Picture> picturePage =
                this.page(new Page<>(pictureQueryRequest.getCurrent(), pictureQueryRequest.getPageSize()),
                        this.getQueryWrapper(pictureQueryRequest));
        // 获取封装类
        Page<PictureVO> pictureVOPage = this.getPictureVOPage(picturePage, request);

        //5.更新缓存
        String cacheValue = JSONUtil.toJsonStr(pictureVOPage);
        //更新本地缓存
        LOCAL_CACHE.put(cacheKey, cacheValue);
        //更新Redis缓存
        //3 - 6 分钟随机过期，防止雪崩
        int cacheExpireTime = 180 + RandomUtil.randomInt(0, 180);
        valueOps.set(cacheKey, cacheValue, cacheExpireTime, TimeUnit.SECONDS);

        //6.返回结果
        return pictureVOPage;
    }

    /**
     * 清理云存储图片
     *
     * @param oldPicture
     */
    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        // 判断该图片是否被多条记录使用
        String pictureUrl = oldPicture.getUrl();
        long count = this.lambdaQuery()
                .eq(Picture::getUrl, pictureUrl)
                .count();
        // 有不止一条记录用到了该图片，不清理
        if (count > 1) {
            return;
        }
        // FIXME 注意，这里的 url 包含了域名，实际上只要传 key 值（存储路径）就够了
        String host = cosClientConfig.getHost(); // 获取域名地址
        // 确保URL以域名地址开头
        if (pictureUrl.startsWith(host)) {
            // 从URL中去掉主机地址部分，剩余部分即为compressCiObject.getKey()
            String compressKey = pictureUrl.substring(host.length() + 1); // 加1是因为要去掉斜杠
            //删除压缩图
            cosManager.deleteObject(compressKey);
            //获得原图key
            String pictureKey = oldPicture.getOriginUrl().substring(host.length() + 1);// 加1是因为要去掉斜杠
            //删除原图
            cosManager.deleteObject(pictureKey);
            String thumbnailUrl = oldPicture.getThumbnailUrl();
            //判断是否存在缩略图
            if (StrUtil.isNotBlank(thumbnailUrl)) {
                String thumbnailUrlKey = thumbnailUrl.substring(host.length() + 1); // 加1是因为要去掉斜杠
                //删除缩略图
                cosManager.deleteObject(thumbnailUrlKey);
            }
        } else {
            System.out.println("URL格式不正确或主机地址不匹配");
        }
    }

    /**
     * 清理云存储图片（批量）
     *
     * @param oldPictureList
     */
    @Async
    @Override
    public void clearPictureFileBatch(List<Picture> oldPictureList) {
        if (oldPictureList == null || oldPictureList.size() <= 0) {
            return;
        }
        for (Picture oldPicture : oldPictureList) {
            // 判断该图片是否被多条记录使用
            String pictureUrl = oldPicture.getUrl();
            long count = this.lambdaQuery()
                    .eq(Picture::getUrl, pictureUrl)
                    .count();
            // 有不止一条记录用到了该图片，不清理
            if (count > 1) {
                return;
            }
            // FIXME 注意，这里的 url 包含了域名，实际上只要传 key 值（存储路径）就够了
            String host = cosClientConfig.getHost(); // 获取域名地址
            // 确保URL以域名地址开头
            if (pictureUrl.startsWith(host)) {
                // 从URL中去掉主机地址部分，剩余部分即为compressCiObject.getKey()
                String compressKey = pictureUrl.substring(host.length() + 1); // 加1是因为要去掉斜杠
                //删除压缩图
                cosManager.deleteObject(compressKey);
                //获得原图key
                String pictureKey = compressKey.substring(0, compressKey.length() - 4);
                //删除原图
                cosManager.deleteObject(pictureKey);
                String thumbnailUrl = oldPicture.getThumbnailUrl();
                //判断是否存在缩略图
                if (StrUtil.isNotBlank(thumbnailUrl)) {
                    String thumbnailUrlKey = thumbnailUrl.substring(host.length() + 1); // 加1是因为要去掉斜杠
                    //删除缩略图
                    cosManager.deleteObject(thumbnailUrlKey);
                }
            } else {
                System.out.println("URL格式不正确或主机地址不匹配");
            }
        }

    }

    /**
     * 校验用户操作图片的权限
     *  TODO 方案1.私有空间，仅空间管理员有权限
     *
     * @param loginUser
     * @param picture
     */
    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            // 公共图库，仅本人或管理员可操作
            if (!picture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
        if (spaceId != null) {
            // TODO 方案1.私有空间，仅本人/空间管理员有权限
            if (!picture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "‘分享链接已失效’/‘私有空间图片，仅本人/空间管理员有权限操作！’");
            }
        }
    }

    /**
     * 删除图片
     *
     * @param pictureId
     * @param loginUser
     */
    @Override
    public void deletePicture(long pictureId, User loginUser) {
        ThrowUtils.throwIf(pictureId <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 判断是否存在
        Picture oldPicture = this.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限
        //改为注解校验权限
//        checkPictureAuth(loginUser, oldPicture);
        // 操作数据库
        Long spaceId = oldPicture.getSpaceId();
        if (spaceId != null) {
            transactionTemplate.execute(status -> {
                boolean result = this.removeById(pictureId);
                ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败，操作数据库失败！");
                boolean delete = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!delete, ErrorCode.OPERATION_ERROR, "删除失败，操作数据库失败！");
                return result;
            });
        } else {
            this.removeById(pictureId);
        }
        //判断是否是公共图库图片
        if (oldPicture.getSpaceId() == null) {
            //清理缓存
            clearCaffineAndRedisCache(RedisKeyConstant.HONE_PAGE_CACHE_KEY,
                    RedisKeyConstant.HONE_PAGE_CACHE_KEY);
        }
        // 异步清理文件
        this.clearPictureFile(oldPicture);
    }

    /**
     * 批量删除图片（删除空间时使用）
     *
     * @param spaceId
     * @param loginUser
     */
    @Override
    public void deletePictureBatch(User loginUser, Long spaceId) {
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        ThrowUtils.throwIf(spaceId == null, ErrorCode.PARAMS_ERROR);
        //查询出一共要删除的图片数量
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .list();
        if (pictureList.size() <= 0) {
            return;
        }
        //操作数据库
        transactionTemplate.execute(status -> {
            //删除数据
            boolean deleteResult = this.lambdaUpdate()
                    .eq(Picture::getSpaceId, spaceId)
                    .remove();
            ThrowUtils.throwIf(!deleteResult, ErrorCode.OPERATION_ERROR, "删除失败，操作数据库失败！");
            return deleteResult;
        });
        // 异步清理文件
        this.clearPictureFileBatch(pictureList);
    }

    /**
     * 用户编辑图片
     *
     * @param pictureEditRequest
     * @param loginUser
     */
    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        // 在此处将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        this.validPicture(picture);
        // 判断是否存在
        long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限
        //改为注解校验权限
//        checkPictureAuth(loginUser, oldPicture);
        // 补充审核参数
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        //判断是否是公共图库图片
        if (oldPicture.getSpaceId() == null) {
            //清理缓存
            clearCaffineAndRedisCache(RedisKeyConstant.HONE_PAGE_CACHE_KEY,
                    RedisKeyConstant.HONE_PAGE_CACHE_KEY);
        }
    }

    /**
     * 清理本地缓存+redis缓存
     *
     * @param caffineCacheKey
     * @param redisCacheKey
     */
    public void clearCaffineAndRedisCache(String caffineCacheKey, String redisCacheKey) {
        //清理本地缓存+redis缓存
        //获取前缀
        String prefix = "zziq-CPB:listPictureVOByPage:forHomePage:currentPage:";
        //使用 keys 方法获取所有匹配的键
        Set<String> keys = stringRedisTemplate.keys(prefix + "*");
        if (keys != null && !keys.isEmpty()) {
            // 删除所有匹配的键
            stringRedisTemplate.delete(keys);
            log.info("redis缓存清理成功！");
        } else {
            log.info("未发现redis缓存。");
        }
        LOCAL_CACHE.invalidateAll();
    }

    // 定义前缀
    String prefix = "zziq-CPB:listPictureVOByPage:forHomePage:currentPage:";
    // 使用 keys 方法获取所有匹配的键


    /**
     * 根据颜色搜索图片
     *
     * @param spaceId
     * @param picColor
     * @param loginUser
     *
     * @return
     */
    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor,
                                                User loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        // 3. 查询该空间下所有图片（必须有主色调）
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        // 如果没有图片，直接返回空列表
        if (CollUtil.isEmpty(pictureList)) {
            return Collections.emptyList();
        }
        // 将目标颜色转为 Color 对象
        Color targetColor = Color.decode(picColor);
        // 4. 计算相似度并排序
        // 定义相似度阈值
        double THRESHOLD = 0.6; // 根据需要调整这个值
        List<Picture> sortedPictures = pictureList.stream()
                .filter(picture -> {
                    String hexColor = picture.getPicColor();
                    // 去掉没有主色调的图片
                    if (StrUtil.isBlank(hexColor)) {
                        return false;
                    }
                    //计算出该图片的颜色值
                    Color pictureColor = Color.decode(hexColor);
                    // 计算相似度
                    double similarity =
                            ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                    // 只保留相似度大于等于阈值的图片
                    return similarity >= THRESHOLD;
                })
                .sorted(Comparator.comparingDouble((Picture picture) -> {
                    // 提取图片主色调
                    String hexColor = picture.getPicColor();
                    Color pictureColor = Color.decode(hexColor);
                    // 越大越相似
                    return ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                }).reversed())
                // 取前 12 个
                .limit(12)
                .collect(Collectors.toList());

        // 转换为 PictureVO
        return sortedPictures.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
    }

    /**
     * 批量编辑图片
     * @param pictureEditByBatchRequest
     * @param loginUser
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();

        // 1. 校验参数
        ThrowUtils.throwIf(spaceId == null || CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }

        // 3. 查询指定图片，仅选择需要的字段
        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();

        if (pictureList.isEmpty()) {
            return;
        }
        // 4. 更新分类和标签
        pictureList.forEach(picture -> {
            if (StrUtil.isNotBlank(category)) {
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });

        // 5.批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);
        // 6. 批量更新
        boolean result = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    /**
     * nameRule 格式：图片{序号}
     *
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (CollUtil.isEmpty(pictureList) || StrUtil.isBlank(nameRule)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }

    /**
     * 发起图片AI扩图任务
     * @param createPictureOutPaintingTaskRequest
     * @param loginUser
     * @return
     */
    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }

    /**
     * 下载图片
     * @param picture
     * @param loginUser
     * @return
     */
    @Override
    public void downloadPicture(Picture picture, User loginUser, boolean isCompress, HttpServletResponse response) throws IOException {
        Integer downloadCount = loginUser.getDownloadCount();
        ThrowUtils.throwIf(downloadCount <= 0, ErrorCode.OPERATION_ERROR, "下载次数不足,可使用兑换码兑换vip身份来提高每天的下载次数");
        // 默认下载原图片
        String downloadUrl = picture.getOriginUrl();
        // 判断是否需要下载压缩图片
        if (isCompress) {
            downloadUrl = picture.getUrl();
        }
        // 获取图片格式(后缀)
        String contentType = downloadUrl.substring(downloadUrl.lastIndexOf('.') + 1);

        // 从URL加载图片
        URL url = new URL(downloadUrl);
        BufferedImage originalImage = ImageIO.read(url);

        // 添加水印
        byte[] watermarkedImageBytes = addWatermark(originalImage, picture);

        // 设置响应头
        response.setContentType("image/png");
        response.getOutputStream().write(watermarkedImageBytes);
        response.getOutputStream().flush();
    }


    /**
     * 给图片添加水印
     * @param originalImage
     * @param picture
     * @return
     * @throws IOException
     */
    private byte[] addWatermark(BufferedImage originalImage,Picture picture) throws IOException {

        // 创建一个新的BufferedImage对象，用于绘制水印
        BufferedImage watermarkedImage = new BufferedImage(
                originalImage.getWidth(),
                originalImage.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = watermarkedImage.createGraphics();
        g2d.drawImage(originalImage, 0, 0, null);

        // 动态计算字体大小
        int baseFontSize = 24; // 基础字体大小
        int dynamicFontSize = Math.max(baseFontSize, originalImage.getWidth() / 30); // 根据图片宽度动态调整字体大小

        // 设置水印的字体、颜色和透明度
        Font font = new Font("simsun", Font.BOLD, dynamicFontSize);
        g2d.setFont(font);
        g2d.setColor(new Color(255, 0, 0, 45)); // 设置为红色，不透明
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));

        // 获取水印文本的尺寸
        FontMetrics fontMetrics = g2d.getFontMetrics(font);
        String watermarkText = "智能云图库平台";
        int textWidth = fontMetrics.stringWidth(watermarkText);
        int textHeight = fontMetrics.getHeight();

        // 计算第一个水印的中心位置
        int x1 = (originalImage.getWidth() - textWidth) / 2;
        int y1 = (originalImage.getHeight() - textHeight) / 2;

        // 在图片上绘制第一个水印文本
        g2d.drawString(watermarkText, x1, y1);

        // 计算第二个水印的位置（在第一个水印的下方）
        String watermarkText2 = picture.getId() + "";
        int textWidth2 = fontMetrics.stringWidth(watermarkText2);
        int textHeight2 = fontMetrics.getHeight();
        int x2 = (originalImage.getWidth() - textWidth2) / 2;
        int y2 = y1 + textHeight + 10; // 第二个水印在第一个水印下方，间隔10像素

        // 在图片上绘制第二个水印文本
        g2d.drawString(watermarkText2, x2, y2);

        // 释放资源
        g2d.dispose();

        // 将处理后的图片转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(watermarkedImage, "png", baos);
        byte[] watermarkedImageBytes = baos.toByteArray();
        return watermarkedImageBytes;
    }
}




